package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Address;
import com.tianxin.workbao.workBao.bean.AddressDao;
import com.tianxin.workbao.workBao.bean.SamplingDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/26.
 */

public class AddressProvide extends BaseDataProvide {
    private Integer mPage;
    private List<Address> mAddressList;
    private int companyid;
    private UpdateListViewListener mUpdateListViewListener;
    private AddressDao addressDao;
    private boolean isGetData = true;
    private boolean isDeletedata = false;



    public AddressProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        addressDao = GreenDaoHelper.newInstance().getDaoSession().getAddressDao();

    }

    private void getFromDb() {
        Query<Address> query = addressDao.queryBuilder().where(SamplingDao.Properties.Isis.eq(1))
                .offset((mPage - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        mAddressList = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (isGetData == false || isDeletedata == true) {
                            mUpdateListViewListener.showMessage("ok");
                            return;
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (mAddressList != null && !mAddressList.isEmpty()) {
                            mAddressList.clear();
                        }
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    mAddressList =  JSON.parseArray(dataJson,Address.class);
                                    refreshUI();
                                    saveToDb(mAddressList);
                                } else {
                                    Address address = JSON.parseObject(dataJson,Address.class);
                                    mAddressList.add(address);
                                    refreshUI();
                                    saveToDb(mAddressList);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("sampling To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        if (isGetData == false || isDeletedata == true) {
                            mUpdateListViewListener.showMessage("failure" + information);
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                        if (mAddressList != null && !mAddressList.isEmpty()) {
                            mAddressList.clear();
                        }
                        refreshUI();
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mAddressList.size(); i++) {
                addressDao.insertOrReplace(mAddressList.get(i));
            }
        } else {
            addressDao.insertOrReplace((Address) obj);
        }
    }

    /**
     * get samplings
     *
     * @param page
     */
    public void getdatas(int companyid ,int page) {
        mPage=page;
        this.companyid = companyid;
        isGetData=true;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb();
            refreshUI();
        } else {
            getFromServer();
        }

    }


    /**
     * update the coal data  from server
     */
    private void getFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("page", mPage + "");
        map.put("companyid", companyid + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getAddressUrl(), params), getDisposeDataHandle());
    }

    @Override
    public void refreshUI() {
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(mAddressList);
        } else {
            mUpdateListViewListener.onRefreshData(mAddressList);
        }
    }

}
